package com.soul.dj.util;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import android.util.Log;

import com.soul.dj.model.User;
import com.soul.dj.util.http.json.JsonProcessUtil;

public class MemeryInfo {

	private static final String TAG = "MemeryInfo";
	private static MemeryInfo instance = new MemeryInfo();
	private GlobalParams globalParams;
	
	private File file = new File(Const.FILE_LOCATION+"/memeryInfo.json");
	
	private MemeryInfo()
	{
		if(!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch(IOException e)
			{
				Log.e(TAG , "创建持久化文件失败！",e);
			}
		}
		globalParams = new GlobalParams();
	}
	
	public static MemeryInfo getInstance()
	{
		instance.init();
		return instance;
	}
	
	public void init()
	{
		try
		{
			String json = FileUtils.readFileToString(file);
			json = json.trim();
			Log.d(TAG , "读取全局持久化文件："+json);
			if(!"".equals(json))
			{
				GlobalParams globalParams = JsonProcessUtil.jsonToBean2(json , GlobalParams.class);
				Log.d(TAG , "解析全局持久化文件成功："+globalParams);
				this.globalParams = globalParams;
			}
		}
		catch(Exception e)
		{
			Log.e(TAG , "读取持久化全局变量失败",e);
		}
	}
	
	public User getUser()
	{
		User bkCfg = globalParams.getUser();
		return bkCfg;
	}
	
	public void setUser(User bkCfg)
	{
		globalParams.setUser(bkCfg);
		saveGlobalParams();
	}

	public Config getConfig()
	{
		Config bkCfg = globalParams.getCfg();
		return bkCfg;
	}

	public void setConfig(Config bkCfg)
	{
		globalParams.setCfg(bkCfg);
		saveGlobalParams();
	}
	
	private void saveGlobalParams()
	{
		try
		{
			String json = JsonProcessUtil.beanToJson(globalParams);
			FileUtils.write(file , json);
		}
		catch(Exception e)
		{
			Log.e(TAG , "写入持久化全局变量失败",e);
		}
	}
	
	
	static class GlobalParams
	{
		// 用户
		private User user;
		//配置
		private Config cfg;

		public User getUser() {
			return user;
		}
		public void setUser(User user) {
			this.user = user;
		}

		public Config getCfg() {
			return cfg;
		}

		public void setCfg(Config cfg) {
			this.cfg = cfg;
		}

		@Override
		public String toString() {
			return super.toString();
		}
	}
}
